class Dialog extends fairygui.GComponent{

    public speed:number = 300;
    public waitTime:number = 1000;
    public view: fairygui.GComponent;
    public txt:fairygui.GRichTextField;
    private _label:string;

    private _animing:boolean;
    private _curTime:number;
    private _lastTime:number;
    private _totalTime:number;
    private _percent:number;
    
    constructor(){
        super();
        this.view = fairygui.UIPackage.createObject("ui","Dialog").asCom;
        //this._view.setSize(fairygui.GRoot.inst.width,fairygui.GRoot.inst.height);
        this.txt = <fairygui.GRichTextField>this.view.getChild("txt");
        this.txt.fontSize = 40;
        this.addChild(this.view);
    }

    public get label():string
    {
        return this._label;
    }
    public set label(v:string)
    {
        this._label = v;
        if(this._label.length > 0)
        {
            this._curTime = 0;
            this._lastTime = 0;
            this._totalTime = this.speed * this._label.length;
            this.start();
            this._animing = true;
        }
        
    }

    private start():void
    {
        if(!this.hasEventListener(egret.Event.ENTER_FRAME))
        {
            this.addEventListener(egret.Event.ENTER_FRAME, this.onTick,this);
        }
    }

    private stop():void
    {
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onTick,this);
        this.txt.text = this.label;
        if(this._animing)
        {
            this._animing = false;
            this.dispatchEvent(new egret.Event(EVENT.DIALOG_OVER))
        }
    }

    public next():void
    {
        if(this._animing)
        {
            this._lastTime = this._totalTime;
        }
    }

    public hide():void
    {
        this.visible = false;
    }
    public show():void
    {
        this.visible = true;
    }
    private onTick(e):void
    {
        this.tick(30);
    }

    private tick(advanceTime:number):void
    {
        this._curTime = this._lastTime + advanceTime;
        this._lastTime = this._curTime;
        if(this._curTime > this._totalTime + this.waitTime)
        {
            this.stop();
        }
        this._percent = this._curTime / this._totalTime;
        if(this._percent > 1)
        {
            this._percent = 1;
        }
        var curLen:number = Math.floor(this._label.length * this._percent);
        var l:string = this._label.substr(0,curLen);
        this.txt.text = l;
    }

}